﻿using MES.Core.Model;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System.Reflection;

namespace MES.Core.Extension
{
    public class ServerDbInit
    {
        /// <summary>
        /// 初始化数据库
        /// </summary>
        public static void ServerBini()
        {
            try
            {
                //先创建主数据库并且创建表
                SqlSugarHelper sqlSugarHelper = new SqlSugarHelper();

                CreateTable(sqlSugarHelper.Db, "MES.Core");

                var list = sqlSugarHelper.Db.Queryable<ConnectionPool>().Where(x => x.IsEnabled == 1).ToList();
                foreach (var item in list)
                {
                    sqlSugarHelper.ChangeDB(item.ConnectionString, item.DbType);
                    CreateTable(sqlSugarHelper.Db, "MES.Model");
                }
                AppSetting.GetService<ILogger<ServerDbInit>>().LogInformation("数据库初始化完成!");

            }
            catch (Exception ex)
            {

                AppSetting.GetService<ILogger<ServerDbInit>>().LogError($"数据库初始化异常!原因:{ex.Message}");
            }

        }

        /// <summary>
        /// 创建数据库表
        /// </summary>
        /// <param name="Db"></param>
        /// <param name="assemblyName"></param>
        private static void CreateTable(SqlSugarClient Db, string assemblyName)
        {

            Db.DbMaintenance.CreateDatabase();
            Type[] typelist = GetTypesWithSugarTableAttributeFromAssembly(assemblyName);

            Db.CodeFirst.InitTables(typelist);

        }

        /// <summary>
        /// 获取指定命名空间下的所有类
        /// </summary>
        /// <param name="assemblyName"></param>
        /// <param name="targetNamespace"></param>
        /// <returns></returns>
        private static Type[] GetTypesWithSugarTableAttributeFromAssembly(string assemblyName, string targetNamespace = null)
        {
            Assembly assembly = Assembly.Load(assemblyName);
            Type[] allTypes = assembly.GetTypes();

            List<Type> resultTypes = new List<Type>();

            foreach (Type type in allTypes)
            {
                if (targetNamespace == null || type.Namespace == targetNamespace)
                {
                    object[] attributes = type.GetCustomAttributes(typeof(SugarTable), false);
                    if (attributes.Length > 0)
                    {
                        resultTypes.Add(type);
                    }
                }
            }

            return resultTypes.ToArray();
        }
    }
}
